<style>

</style>
<template>
  <el-dialog
    title="元数据配置"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    width="60%"
    :before-close="clearForm">

    <el-form
      :label-position="labelPosition"
      label-width="100px"
      :model="saveData"
      :rules="rules"
      ref="ruleForm"
    >
      <el-form-item label="选择域" prop="domainCode">
        <el-select
          :disabled="saveData.id && saveData.id !==''"
          filterable
          v-model="saveData.domainCode"
          placeholder="请选择域">
          <el-option
            v-for="item in domainOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="元数据名称" prop="metadataName">
        <el-input :disabled="saveData.id && saveData.id !==''" v-model="saveData.metadataName"></el-input>
      </el-form-item>
      <el-form-item label="元数据描述">
        <el-input v-model="saveData.desc"></el-input>
      </el-form-item>

      <el-form-item label="键值对" required>
        <template v-for="(item,index) in saveData.metadataPairs">
          <el-form :rules="metadataPairRules"
                   style="margin-bottom: 15px"
                   :inline="true"
                   ref="scenePairForm"
                   :model="item"
                   label-width="80px">
            <el-form-item label="Key" prop="key">
              <el-input v-model="item.key"></el-input>
            </el-form-item>
            <el-form-item label="Value" prop="value">
              <el-input v-model="item.value"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-button
                v-if="index === 0"
                type="primary"
                icon="el-icon-plus" circle
                size="mini"
                @click="addMetadataPair">
              </el-button>
              <el-button v-if="index !== 0"
                         type="danger"
                         icon="el-icon-delete" circle
                         size="mini"
                         @click="removeMetadataPair(index)">
              </el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="clearForm">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
  </el-dialog>
</template>
<script>

import {remoteValidateMetadataName, saveMetadata} from "../../../api/metadataApi";
import {loadDomainSelector} from "../../../api/loadSelectorApi";

export default {
  name: "metadataForm",
  filters: {},
  components: {},
  data() {
    const validateMetadataName = async (rule, value, callback) => {
      if (this.saveData.id) {
        callback()
      }
      if (!this.saveData.domainCode) {
        callback(new Error("域必须先选择"))
      }
      let ret = await remoteValidateMetadataName(value, this.saveData.domainCode);
      if (ret.data.result) {
        callback()
      } else {
        callback(new Error("元数据名字不能重复"))
      }
    };
    const validateMetadataKey = (rule, value, callback) => {
      let vm = this
      let size = 0
      for (let i = 0; i < vm.saveData.metadataPairs.length; i++) {
        if (vm.saveData.metadataPairs[i].key === value) {
          size++
        }
      }
      if (size > 1) {
        callback(new Error(value + " 不能有多个"))
      }
    };
    const validateMetadataValue = (rule, value, callback) => {
      let vm = this
      let size = 0
      for (let i = 0; i < vm.saveData.metadataPairs.length; i++) {
        if (vm.saveData.metadataPairs[i].value === value) {
          size++
        }
      }
      if (size > 1) {
        callback(new Error(value + " 不能有多个"))
      }
    };

    return {
      labelPosition: 'right',
      dialogVisible: false,
      saveData: {
        domainCode: '',
        metadataName: '',
        desc: '',
        metadataPairs: [
          {sceneName: "", sceneCode: ""}
        ]
      },
      domainOptions: [],
      rules: {
        metadataName: [
          {required: true, message: '此项必填', trigger: 'blur'},
          {validator: validateMetadataName, trigger: 'blur'}
        ],
        domainCode: [
          {required: true, message: '此项必填', trigger: 'change'},
        ]
      },
      metadataPairRules: {
        key: [
          {required: true, message: '此项必填', trigger: 'blur'},
          {validator: validateMetadataKey, trigger: 'blur'}
        ],
        value: [
          {required: true, message: '此项必填', trigger: 'blur'},
          {validator: validateMetadataValue, trigger: 'blur'}
        ],
      }
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    async load(data) {
      let vm = this
      if (data) {
        vm.saveData = vm.$cloneObj(data)
      }
      vm.domainOptions = await loadDomainSelector()
      vm.dialogVisible = true
    },
    save() {
      let vm = this
      console.log(1)
      vm.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let validateRes = true
          for (let i = 0; i < vm.$refs['scenePairForm'].length; i++) {
            vm.$refs['scenePairForm'][i].validate((v) => {
              if (!v) {
                validateRes = valid
              }
            })
          }
          if (validateRes) {
            await vm.doSave(this.saveData)
          }
        }
      })
    },
    async doSave(saveData) {
      let vm = this
      let ret = await saveMetadata(saveData);
      if (ret.ok) {
        vm.$message({type: 'success', message: '保存成功!'});
      } else {
        vm.$message({type: 'error', message: '保存失败：' + ret.message});
      }
      vm.clearForm()
      vm.$parent.query()
    },
    clearForm() {
      let vm = this
      try {
        vm.$refs['ruleForm'].resetFields()

        for (let i = 0; i < vm.$refs['scenePairForm'].length; i++) {
          vm.$refs['scenePairForm'][i].resetFields()
        }
      } catch (e) {
        console.log(e)
      }
      vm.saveData = {
        domainCode: '',
        metadataName: '',
        desc: '',
        metadataPairs: [
          {sceneName: "", sceneCode: ""}
        ]
      }
      vm.dialogVisible = false
    },
    addMetadataPair() {
      this.saveData.metadataPairs.push({sceneName: "", sceneCode: ""})
    },
    removeMetadataPair(index) {
      this.saveData.metadataPairs.splice(index, 1);
    }
  }
}
</script>
